
var pageBean = null;
var dataList = {};
var provinces = {};
var cities = {};
var citySpace = {};
var spaces = {};
var roomTypes = {};
var selRoom = null;
var selRoomId = null;
var seatCount = 0;
var seatUsed = 0;


$(document).ready(function(e) {
	 $(".select1").uedSelect({
			width : 345			  
	});
	$(".select2").uedSelect({
		width : 167  
	});
	$(".select3").uedSelect({
		width : 100
	});
	$("div[name='noSpace']").show();
	$("div[name='noRoom']").hide();
	$("div[name='something']").hide();
	
	
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#btnDelete").click(deleteData);
	
	$("#add").click(add);
	initialPlaces();
	
	$("SELECT[name='placeProvinceSelect']").change(provinceChange);	
	$("SELECT[name='placeCitySelect']").change(initialSpace);
	$("SELECT[name='spaceSelect']").change(spaceChange);
	initialRoomType();
});

function getRequestJson(requestJson,act){	
	if(requestJson == null){
		requestJson = {};
	}
	var addroomType = $("#addroomType").val();
	if(addroomType == '-1'&&act=='save'){
		alert("请选择房间类型");
		return false;
	}
	$("[formParameter]").each(function(index,element){
		try{
			var required = $(element).prop("required");
			var val = $(element).val();
			var name = $(element).attr("name");
			if(required == '1' && $.trim(val) == '' &&act=='save'){
				var message = $(element).attr("message");
				alert(message);
				requestJson = false;
				return false;
			}
			if(name == 'roomType'){
				requestJson[name] = roomTypes[val];
			}else{
				requestJson[name] = $(element).val();
			}
		}catch(e){
			//alert(e.message);
		}
	});
	if(requestJson != false){
		var mSpace = spaces[$("#searchSpace").val()];		
		requestJson["space"] = mSpace;
		try{
			requestJson["province"] = mSpace.province;
			requestJson["city"] = mSpace.city;
		}catch(e){
			console.log(e.message);
		}		
//		requestJson["province"] = provinces[$("#searchProvince").val()];		
//		requestJson["city"] = cities[$("#searchCity").val()];		
		
	}
	return requestJson;
}



function save(){
	
	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	//alert(JSON.stringify(requestJson));
	$.ajax({
        url: '/euc/room/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='dataList']").show();
        	$("DIV[name='dataAdd']").hide();
        	//closeModalDialog();
        	search(1);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function update(data,act){
	if(data == null){
		return false;
	}
	data = getRequestJson(data,act);
	if(data == false ){
		return false;
	}
	
	
	$.ajax({
        url: '/euc/room/update',
        data:JSON.stringify(data),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='dataList']").show();
        	$("DIV[name='dataAdd']").hide();
        	//closeModalDialog();
        	search(1);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataAdd']").hide();
}

function clearSpace(){
	$("[formParameter]").each(function(index,element){		
		try{
			$(element).val('');
		}catch(e){
			//alert(e.message);
		}
	});
	if($("#searchSpace").val() == '0'){
		alert("请选择空间");
		return false;
	}else{
		$("#formSpaceName").html(spaces[$("#searchSpace").val()].spaceName);
	}
	return true;
}

function setSpace(data){
	$("[formParameter]").each(function(index,element){
		try{
			var tagName = $(element).prop("tagName");
			if(tagName == 'SELECT'){				
				$(element).val(data[$(element).attr("name")].id).trigger('change');
			}else{
				$(element).val(data[$(element).attr("name")]);
			} 
		}catch(e){
			//alert(e.message);
		}
	});
}

function add(){
	if(clearSpace() == false){
		return false;
	}
	$("#btnDelete").hide();
	$("#operator").html("添加");	
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataAdd']").show();

	$("#addroomType").val("-1").trigger("change");
	//popupModalDialog();
}


function detail(){
	if(selRoom != null){
		$("#btnDelete").show();
		clearSpace();
		setSpace(selRoom);
		$("#operator").html("编辑");
		$("DIV[name='dataList']").hide();
		$("DIV[name='dataAdd']").show();	
		//popupModalDialog();
		$("#btnSave").unbind();
		$("#btnSave").click(function(){
			var currentRoom = dataList[selRoomId];
			update(currentRoom,'save');
		});
	}	
}

function deleteData(){
	if(selRoomId != null){
		if(confirm("确定删除该记录?")){
			var currentRoom = dataList[selRoomId];
			currentRoom["enable"] = false;
			update(currentRoom,'del');
		}
	}	 
}


function search(currentPage){	
	var parameter = $("INPUT[name='parameter']").val();
	var provinceId = $("#searchProvince").val();
	// if(provinceId == '0'){
	// 	alert("请选择省");
	// 	return;
	// }
	// var cityId = $("#searchCity").val();
	// if(cityId == '0'){
	// 	alert("请选择市");
	// 	return;
	// }
	var spaceId = $("#searchSpace").val();
	if(spaceId == '0'){
		alert("请选空间");
		return;
	}
	// var requestJson = {currentPage:currentPage,data:{like:{roomName:parameter},equals:{'enable':true,'province.provinceId':provinceId,'city.cityId':cityId,'space.id':spaceId}}};
	var requestJson = {currentPage:currentPage,data:{like:{roomName:parameter},equals:{'enable':true,'space.id':spaceId}}};
	$.ajax({
        url: '/euc/room/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	pageBean = result.data;
        	$("#roomList").empty();	  
        	seatCount = 0;
        	seatUsed = 0;
        	$.each(result.data.list,function(i,data){        		
        		var cls = "unusedlarge";
        		try{
        			if(data.contractProducts.length > 0){
            			cls = "usedlarge";
            			seatUsed += data.seatCount;
            		}
        			$.each(data.contractProducts,function(i,contractProduct){
        				if(contractProduct.willOver == 'true' || contractProduct.willOver == true){
        					cls = "dangerlarge";
        				}
        			});
        		}catch(e){
        			// console.log(e.message);
        		}
        		
				var html = '<button  type="button" name="room" id="'+data.id+'"  title="'+data.roomPrice+'元/月" class="'+cls+'">'+  data.roomName + '<br/>'+ data.roomType.roomTypeName +'</button>';
	        	$("#roomList").append(html);
	        	dataList[data.id] = data;
	        	if (typeof(data.seatCount) == "undefined" || data.seatCount == ''){ 
        			seatCount = seatCount + 0;
        		}else{
        			seatCount = seatCount + data.seatCount;
        		}
			});
        	
        	if(result.data.list.length > 0){
        		$("div[name='noSpace']").hide();
            	$("div[name='noRoom']").hide();
            	$("div[name='something']").show();
        	}else{
        		$("div[name='noSpace']").hide();
            	$("div[name='noRoom']").show();
            	$("div[name='something']").hide();
        	}
        	selRoom = null;
        	if($("button[name='room']").length > 0){
        		$("button[name='room']").click(roomclick);
        		$("button[name='room']").eq(0).trigger("click");
        	}
        	$("#usagerate").html('入住率：'+((seatUsed*100)/seatCount).toFixed(2)+'%');
        	$("#seatCount").html('工位数：'+seatUsed+'/'+seatCount);
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function roomclick(){
	try{
		var id = $(this).prop("id");
		selRoom = dataList[id];
		selRoomId = id;
		$("#detailButton").prop('roomid',selRoom.id);
		$("#detailroomName").html(selRoom.roomName);		
		$("#detailseatCount").html(selRoom.seatCount);
		$("#detailclient").html('');
		$("#detailperiod").html('');
		$("#detailOrderNumber").html('');
		$("#detailWaitBills").html('0份');
		$(".btnView").html('');
		$.ajax({
	        url: '/euc/room/detail',
	        data:JSON.stringify({'roomId':id}),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	// console.log(JSON.stringify(result));
	        	var clientInfo = $("#clientInfoRight");
	        	$(clientInfo).find("div[clientInfo='1']").remove();
	        	var clientId = '';
	        	$.each(result.data.client,function(index,client){
	        		if(clientId != client.id){	        			
		        		var clientName = client.memberName;
		        		if(client.clientType == '企业'){
		        			clientName = client.companyName;
		        		}
		        		$.each(client.orderList,function(orderIndex,order){
		        			$.each(order.contractList,function(contractIndex,contract){
		        				var billCount = 0;
		        				$.each(contract.contractHirePurchaseList,function(hirePurchaseIndex,hirePurchase){
		        					if(hirePurchase.hirePurchaseAmount != hirePurchase.realPaymentAmount){
		        						billCount++;
		        					}	        					
		        				});
		        				$.each(contract.contractProductList,function(productIndex,product){
		        					if(id == product.roomId){
		        						var html = '';
		        		        		html += '<div class="col-md-12 column" clientInfo="1">';
		        		        		html += '<p style="float:left;" class="indInput contentlong col-md-12 column" >入驻客户：<span class="indSpan" style="display: inline;" id="detailclient">'+clientName+'</span></p>';
		        		        		html += '<p style="float: left;" class="indInput contentlong col-md-12 column" >入驻周期：<span class="indSpan" style="display: inline;" id="detailperiod">'+product.rentStart+'--'+product.rentEnd+'</span></p>';
		        		        		html += '</div>';
		        		        		html += '<div class="contentButton col-md-12 column" clientInfo="1">';
		        		        		html += '<p style="float: left;" class="indInput contentlong col-md-12 column" >合同编号：<span class="indSpan"  style="display: inline;" id="detailOrderNumber">'+contract.contractNumber+'</span></p>';
		        		        		/*html += '<input style="float: left;" name="" onclick=" " type="button" class="indInput scbtn" value="查看"/>';*/
		        		        		html += '</div>';
		        		        		html += '<div class="contentButton col-md-12 column" clientInfo="1">';
		        		        		html += '<p style="float: left;" class="indInput contentlong col-md-12 column" >待处理账单：<span class="indSpan"  style="display: inline;" id="detailWaitBills">'+billCount+'份</span></p>';
		        		        		/*html += '<input style="float: left;" name="" onclick=" " type="button" class="indInput scbtn" value="处理"/>';*/
//		        		        		html += '</div><div class="contentButton col-md-12 column btnView" clientInfo="1"><center><a style="float: left;color:#00a4ac;cursor: pointer;font-size: 14px;font-weight: bold;">查看详情</a>';
//		        		        		html += '<a style="color: #00a4ac;cursor: pointer;font-size: 14px;font-weight: bold;">查看会员</a>';
//		        		        		html += '<a style="float: right;color:#00a4ac;cursor: pointer;font-size: 14px;font-weight: bold;">查看账单</a></center>';
		        		        		html += '</div></div>';
		        		        		$(clientInfo).append(html);
		        					}
		        				});
		        			});    
		        		});
		        	}
	        		clientId = client.id;
	        	});
	        },
	        error: function () {
	        	// console.log("error");
	        }  
	    });
	}catch(e){console.log(e.message);}
}



function initialPlaces(){
	$.ajax({
        url: '/euc/space/province',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var provinceSelect = $("SELECT[name='placeProvinceSelect']");        	
        	$.each(result,function(index,data){	
           		$('<option value="'+ data.provinceId +'">'+ data.provinceName +'</option>').appendTo($(provinceSelect));
           		provinces[data.provinceId] = data;
           		var citiesSelect = $("SELECT[name='placeCitySelect']");           		
           		$.each(data.cities,function(index,city){	
    	       		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
    	       		cities[city.cityId] = city;	
    			});
   			});	   
        	$("#searchProvince").val(0).trigger("change");
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function provinceChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var citiesSelect = $("SELECT[name='placeCitySelect']");
	$(citiesSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(citiesSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		if(province){
			$.each(province.cities,function(index,data){	
	       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(citiesSelect));
			});			
		}

	}
	$(citiesSelect).val(0).trigger('change');
}

function initialRoomType(){

	var roomTypeSelect = $("SELECT[name='roomType']");	
	var firstOptionValue = 0;
	$.ajax({
        url: '/euc/roomtype/list',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	$.each(result,function(index,data){	
        		if(index == 0){
        			firstOptionValue = data.id;
        		}        		
           		$('<option value="'+ data.id +'">'+ data.roomTypeName +'</option>').appendTo($(roomTypeSelect));
           		roomTypes[data.id] = data;
        	});
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	if(firstOptionValue != 0){
		$(spaceSelect).val(firstOptionValue).trigger('change');
	}

    var spaceSelect = $("SELECT[name='spaceSelect']");
    //获取全部空间列表
    $.ajax({
        url: '/euc/space/list',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	// console.info(result);
            $.each(result,function(index,data){
                if(index == 0){
                    firstOptionValue = data.id;
                }
                $('<option value="'+ data.id +'">'+ data.spaceName +'</option>').appendTo($(spaceSelect));
                spaces[data.id] = data;
            });
        },
        error: function () {
			/*alert("error");*/
        }
    });
}


function initialSpace(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceSelect));	
	if(cityIdSelected == '0'){
		$(spaceSelect).val(0).trigger('change');
		return;		
	}
	var spacesList = citySpace[cityIdSelected];
	if(spacesList == null){
		var requestJson = {data:{like:{spaceName:''},equals:{'city.cityId':cityIdSelected}}};
		$.ajax({
	        url: '/euc/space/find',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: false,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	//alert(JSON.stringify(result));
	        	citySpace[cityIdSelected] = result;
	        	spacesList = result;
	        },
	        error: function () {
	        	/*alert("error");*/
	        }  
	    });
	} 	
	$.each(spacesList,function(index,data){	
   		$('<option value="'+ data.id +'">'+ data.spaceName +'</option>').appendTo($(spaceSelect));
   		spaces[data.id] = data;
	});
	$(spaceSelect).val(0).trigger('change');
}

function spaceChange(){
	var spaceId=$(this).children('option:selected').val();
	if(spaceId != '0'){
		$("div[name='noSpace']").show();
		$("div[name='noRoom']").hide();
		$("div[name='something']").hide();
	}else{
		$("div[name='noSpace']").show();
		$("div[name='noRoom']").hide();
		$("div[name='something']").hide();
	}
}
